/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 *
 * 			http://www.kkkd.com/
 *
 * ========================================================
 */
package com.simon.mengkou.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.GridView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.ouertech.android.agm.lib.base.future.core.AgnettyFuture;
import com.ouertech.android.agm.lib.base.future.core.AgnettyResult;
import com.ouertech.android.agm.lib.base.utils.UtilList;
import com.ouertech.android.agm.lib.ui.base.defaults.activity.BaseTopActivity;
import com.simon.mengkou.R;
import com.simon.mengkou.data.bean.base.Product;
import com.simon.mengkou.data.bean.base.WishProduct;
import com.simon.mengkou.data.cache.DataCacheImpl;
import com.simon.mengkou.data.enums.EDirection;
import com.simon.mengkou.future.base.OuerFutureListener;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.ui.adapter.ProductAdapter;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * @author : Zhenshui.Xia
 * @since : 2016/3/20.
 * desc    : 商品列表界面
 */
public class ProductListActivity extends BaseTopActivity
        implements PullToRefreshBase.OnRefreshListener2<GridView>{
    @Bind(R.id.common_pulltorefresh_id_grid)
    PullToRefreshGridView mPtrView;

    private ProductAdapter mAdapter;
    private int mPage = 0;
    private String mTitle;
    //商品分类ID
    private String mCategoryId;

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        Intent intent = getIntent();
        mTitle = intent.getStringExtra(CstOuer.KEY.TITLE);
        mCategoryId = intent.getStringExtra(CstOuer.KEY.ID);
    }

    @Override
    protected void initTop() {
        setTitle(mTitle);
        setNavigation(R.drawable.common_ic_left_nav);
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.layout_common_pulltorefresh_grid);
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);

        mPtrView.setOnRefreshListener(this);
        mPtrView.setMode(PullToRefreshBase.Mode.DISABLED);
        mPtrView.setTag(false);

        mAdapter = new ProductAdapter(this);
        mPtrView.setAdapter(mAdapter);


        //获取缓存
        List<Product> datas = OuerApplication.mCacheFactory
                .getCache(DataCacheImpl.ProductListCache.class, mCategoryId)
                .getData();

        if(UtilList.isNotEmpty(datas)) {
            mAdapter.setList(datas);
            mPtrView.setTag(true);
            mPtrView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        } else {
            mPtrView.setTag(false);
            //首次失败重试
            setOnRetryListener(new OnRetryListener() {
                @Override
                public void onRetry() {
                    getData(0, EDirection.REFRESH);
                }
            });
        }

        //获取数据
        getData(0, EDirection.REFRESH);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
        //下拉刷新
        getData(0, EDirection.REFRESH);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
        //上拉加载更多
        getData(mPage + 1, EDirection.LOADMORE);
    }

    /**
     * 获取新粉丝消息
     * @param page
     * @param direction
     */
    private void getData(final int page, final int direction) {
        AgnettyFuture future = OuerApplication.mOuerFuture.buyGoodsList(
                mCategoryId,
                page,
                CstOuer.PAGE.DEFAULT_SIZE,
                new OuerFutureListener(this){

                    public void onStart(AgnettyResult result) {
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            setLoading(true);
                        }
                    }

                    @Override
                    public void onComplete(AgnettyResult result) {
                        super.onComplete(result);
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            mPtrView.setTag(true);
                            setLoading(false);
                        } else {
                            mPtrView.onRefreshComplete();
                        }

                        List<Product> datas = (List<Product>) result.getAttach();

                        if(direction == EDirection.REFRESH) {
                            OuerApplication.mCacheFactory.getCache(DataCacheImpl.ProductListCache.class, mCategoryId)
                                    .save(datas);
                            mPage =0;

                            if(UtilList.isEmpty(datas)) {
                                mPtrView.setMode(PullToRefreshBase.Mode.DISABLED);
                                setEmptyText(R.string.common_empty_data);
                                mAdapter.clearAll();
                            } else {
                                if(UtilList.getCount(datas) < CstOuer.PAGE.DEFAULT_SIZE) {
                                    mPtrView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                                } else {
                                    mPtrView.setMode(PullToRefreshBase.Mode.BOTH);
                                }

                                mAdapter.setList(datas);
                            }
                        } else {
                            int count = UtilList.getCount(datas);
                            //设置最新的max id
                            if(count != 0) {
                                mPage++;
                            }

                            //数据已读取完
                            if(count < CstOuer.PAGE.DEFAULT_SIZE) {
                                mPtrView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            }

                            mAdapter.addList(datas);
                        }
                    }

                    public void onNetUnavaiable(AgnettyResult result) {
                        super.onNetUnavaiable(result);
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            setRetry(true);
                        } else {
                            mPtrView.onRefreshComplete();
                        }
                    }

                    @Override
                    public void onException(AgnettyResult result) {
                        super.onException(result);
                        boolean flag = (Boolean)mPtrView.getTag();
                        if(!flag) {
                            setRetry(true);
                        } else {
                            mPtrView.onRefreshComplete();
                        }
                    }
                });

        attachDestroyFutures(future);
    }
}
